/*
 * Copyright (C) 2014 Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.bambole.controller;

import com.googlecode.bambole.controller.util.ConfigurationUtil;
import com.googlecode.bambole.util.EntryFormatUtil;
import com.googlecode.bambole.domain.User;
import com.googlecode.bambole.controller.util.JsfUtil;
import com.googlecode.bambole.controller.util.PaginationUtil;
import com.googlecode.bambole.util.PasswordUtil;
import com.googlecode.bambole.facade.UserFacade;

import java.io.Serializable;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

/**
 *
 * @author Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 */
@Named("userController")
@SessionScoped
public class UserController implements Serializable {

    private User current;
    private DataModel items = null;

    @EJB
    private com.googlecode.bambole.facade.UserFacade ejbFacade;

    private PaginationUtil pagination;
    private String currentStoredPassword;
    private String query;
    private int selectedItemIndex;
    private int recordCount;

    public UserController() {

    }

    public User getSelected() {
        if (current == null) {
            current = new User();
        }
        return current;
    }

    public void setSelected(User current) {
        this.current = current;
    }

    private UserFacade getFacade() {
        return ejbFacade;
    }

    public boolean isPaginationFromSearch() {
        return !getQuery().equals(getDefaultQuery());
    }

    public PaginationUtil getPagination() {
        if (pagination == null) {
            pagination = new PaginationUtil(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count(getQuery());
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, getQuery()));
                }
            };
        }
        return pagination;
    }

    public String refreshList() {
        query = null;
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareList() {
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareView() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        recordCount = getFacade().count(getQuery());

        return "view.xhtml?faces-redirect=true";
    }

    public String prepareCreate() {
        current = new User();

        current.setLocale(ConfigurationUtil.getDefaultLocale().toLanguageTag());
        current.setTheme(ConfigurationUtil.getDefaultTheme());

        return "create.xhtml?faces-redirect=true";
    }

    public String create() throws Exception {

        if (!validateRecord()) {
            return null;
        }

        Date date = new Date();
        User user = (User) JsfUtil.getSessionParameter("user");
        current.setCreated(date);
        current.setCreatedBy(user);
        current.setUpdated(date);
        current.setUpdatedBy(user);
        current.setPassword(PasswordUtil.getSaltedHashPassword(current.getPassword()));

        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String prepareEdit() {

        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));

            return null;
        }
        currentStoredPassword = current.getPassword();

        return "edit.xhtml?faces-redirect=true";
    }

    public String update() throws Exception {

        if (!validateRecord()) {
            return null;
        }

        Date date = new Date();

        current.setUpdated(date);
        current.setUpdatedBy((User) JsfUtil.getSessionParameter("user"));

        if (isPasswordUpdated()) {
            current.setPassword(PasswordUtil.getSaltedHashPassword(current.getPassword()));
            current.setLastPasswordChange(date);
        }

        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));

            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));

            return null;
        }
    }

    public String destroy() {

        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        User userLoggedIn = (User) JsfUtil.getSessionParameter("user");
        if (current.getId() == userLoggedIn.getId()) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("DeleteCurrentUserError"));

            return null;
        }

        performDestroy();
        recreatePagination();
        recreateModel();

        return "list.xhtml?faces-redirect=true";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
        }
    }

    public DataModel getItems() {

        if (items == null) {
            items = getPagination().createPageDataModel();
        }

        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {

        getPagination().nextPage();
        recreateModel();

        return "list.xhtml?faces-redirect=true";
    }

    public String previous() {

        getPagination().previousPage();
        recreateModel();

        return "list.xhtml?faces-redirect=true";
    }

    public User getUser(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    public String getGeneratedPassword() {
        return PasswordUtil.generateRandomPassword();
    }

    private boolean isPasswordUpdated() {
        return !current.getPassword().equals(currentStoredPassword);
    }

    public void setSelectedItemIndex(int selectedItemIndex) {
        this.selectedItemIndex = selectedItemIndex + pagination.getPageFirstItem();
    }

    public boolean isHasNextRecord() {
        return selectedItemIndex + 2 <= recordCount;
    }

    public boolean isHasPreviousRecord() {
        return selectedItemIndex > 0;
    }

    public String nextItem() {

        selectedItemIndex++;

        if (selectedItemIndex < recordCount) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery()).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    public String previousItem() {

        selectedItemIndex--;

        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery()).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    private boolean validateRecord() {

        boolean retVal = true;

        if (!current.isEnabled() && !getFacade().isAtLeastOneUserEnabled(current.getId() == null ? -1 : current.getId())) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("LastEnabledRecordCannotBeDisabled"));

            retVal = false;
        }

        if (current.getPassword() != null && !current.getPassword().isEmpty()) {

            if (isPasswordUpdated() && !PasswordUtil.isPasswordFormatValid(current.getPassword())) {

                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidPassword"));

                retVal = false;
            }
        }

        if (!EntryFormatUtil.isEmailAddressFormatValid(current.getEmailAddress())) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidEmailAddress"));

            retVal = false;
        }

        if (!getFacade().isEmailAddressUnique(current.getEmailAddress(), current.getId() == null ? -1 : current.getId())) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("EmailAddressAlreadyExists"));

            retVal = false;
        }

        return retVal;
    }

    private String getQuery() {
        return query == null ? getDefaultQuery() : query;
    }

    private String getDefaultQuery() {
        return "SELECT u FROM User u";
    }

    public String prepareSearch() {
        current = new User();

        return "search.xhtml?faces-redirect=true";
    }

    public String performSearch() {

        boolean queryAddAnd = false;
        query = "SELECT u FROM User u";

        if ((current.getName() != null && !current.getName().isEmpty())
                || (current.getDescription() != null && !current.getDescription().isEmpty())
                || (current.getLocale() != null && !current.getLocale().isEmpty())
                || (current.getTheme() != null && !current.getTheme().isEmpty())
                || (current.getEmailAddress() != null && !current.getEmailAddress().isEmpty())) {

            query = query + " WHERE ";

            if (current.getName() != null && !current.getName().isEmpty()) {
                queryAddAnd = true;
                query = query + "u.name LIKE \'%" + current.getName() + "%\'";
            }

            if (current.getDescription() != null && !current.getDescription().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "u.description LIKE \'%" + current.getDescription() + "%\'";
            }

            if (current.getLocale() != null && !current.getLocale().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "u.locale = \'" + current.getLocale() + "\'";
            }

            if (current.getTheme() != null && !current.getTheme().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "u.theme = \'" + current.getTheme() + "\'";
            }

            if (current.getEmailAddress() != null && !current.getEmailAddress().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                }
                query = query + "u.emailAddress LIKE \'%" + current.getEmailAddress() + "%\'";
            }
        }

        recreatePagination();
        recreateModel();

        return "list.xhtml?faces-redirect=true";
    }

    public Locale getLocale() {
        return current.getLocale() == null ? null : Locale.forLanguageTag(current.getLocale());
    }

    public void setLocale(Locale locale) {
        current.setLocale(locale == null ? null : locale.toLanguageTag());
    }
}
